package com.archeanx.libx.http;

import java.util.ArrayList;
import java.util.List;

import okhttp3.Cookie;
import okhttp3.CookieJar;
import okhttp3.HttpUrl;

/**
 *
 */
public class XCookieJarImpl implements CookieJar {

    List<Cookie> cookieStore = new ArrayList<>();

    @Override
    public void saveFromResponse(HttpUrl url, List<Cookie> cookies) {
        cookieStore.addAll(cookies);
    }

    @Override
    public List<Cookie> loadForRequest(HttpUrl url) {
        List<Cookie> matched = new ArrayList<>();

        List<Cookie> cookies = new ArrayList<>();
        cookies.addAll(cookieStore);

        for (Cookie cookie: cookies) {
            //check if cookie is expired or not
            if (cookie.expiresAt() < System.currentTimeMillis()) {
                cookieStore.remove(cookie);
            } else if (cookie.matches(url)) {
                matched.add(cookie);
            }
        }
        return matched;
    }

}
